import { BASE_URL } from "./config"

class ZbRequest {
  constructor(baseUrl) {
    this.baseUrl = baseUrl
  }

  request(url, method, data, config) {
    return new Promise((resolve, reject) => {
      const token = uni.getStorageSync('token')
      const header = {
        ...config.header
      }

      if (token) {
        header["Authorization"] = token
      }
      try {
        uni.request({
          url: this.baseUrl + url,
          data,
          method,
          header,
          success: (res) => {
            resolve(res.data)
          },
          fail: (err) => {
            reject(err)
          }
        })
      }
      catch (e) {
        console.log(e)
      }
    })
  }

  get(url, data) {
    return this.request(url, 'GET', data, { header: { "Content-Type": "application/json" } })
  }

  post(url, data) {
    return this.request(url, 'POST', data, { header: { "Content-Type": "application/x-www-form-urlencoded" } })
  }

  delete(url, data) {
    return this.request(url, 'DELETE', data, {})
  }

  put(url, data) {
    return this.request(url, 'PUT', data, { header: { "Content-Type": "application/json" } })
  }

}

export default new ZbRequest(BASE_URL)
